import { useRef, useState, useEffect } from 'react';
import { ProTable } from '@ant-design/pro-components';
import { DownOutlined } from '@ant-design/icons';
import { Tag, Modal, message, Form, Input, Button, Menu, Dropdown } from 'antd';
import { history } from 'umi';
import { PageContainer } from '@ant-design/pro-components';
import { activatecodeSearch, storeActivate, unlockActivate } from '@/services/sensitizeManage';
import {
  productkeySearch,
  activityCount,
  syncActivity,
  ruleCount,
  syncRule,
  refreshActivity,
  exportProfile,
  exportActivity,
  exportRule,
  productkeyDelete,
  syncUat,
} from '@/services/profile';
import StorageManager from '@/utils/StorageManager';

import type { ParamsType } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-table';
import type { PaginationProps, FormInstance } from 'antd';
import type { ActionType } from '@ant-design/pro-components';

import styles from './style.less';

const { confirm } = Modal;

const SensitizeManageList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [valueEnumActivityId, setValueEnumActivityId] = useState({});
  const [confirmLoad, setConfirmLoad] = useState<boolean>(false);
  const [modelCountVisible, setModelCountVisible] = useState<boolean>(false);
  const [modalCountForm] = Form.useForm();
  const [modelRuleVisible, setModelRuleVisible] = useState<boolean>(false);
  const [modalRuleForm] = Form.useForm();
  const [modelReshVisible, setModelReshVisible] = useState<boolean>(false);
  const [modalReshForm] = Form.useForm();
  const [businessTypeList, setBusinessTypeList] = useState<any>();
  const [sunDetail, setSunDetail] = useState<any>({});
  const [sunDetailBro, setSunDetailBro] = useState<any>({});

  const eunmList: any = StorageManager.getLocalStorageSync('eunmList');

  useEffect(() => {
    const obj: any = {};
    eunmList?.OptionsPlaceBrandList.forEach((item: any) => {
      obj[item.value] = {
        text: item.label,
      };
    });
    setValueEnumActivityId({
      ALL: {
        text: 'ALL',
      },
      ...obj,
    });
  }, []);

  // 提交
  const handleOperate = async (record: any, type: string) => {
    if (type === '同步activity') {
      const { code, data } = await activityCount({ id: record.id });
      setModelCountVisible(true);
      if (code === 200 && data) {
        modalCountForm.setFieldsValue({
          id: record.id,
          productKeyName: record.productKeyName,
          profileCount: data.profileCount,
          activityCount: data.activityCount,
          couponCount: data.couponCount,
          primeCount: data.primeCount,
        });

        setBusinessTypeList(data.businessTypeInfos ? data.businessTypeInfos : []);
        // setBusinessTypeList([
        //   {
        //     type: 'Prime卡套',
        //     count: 1,
        //   },
        //   {
        //     type: '券',
        //     count: 1,
        //   },
        // ]);
        // "businessTypeInfos": ,
      }
      return;
    }

    if (type === '同步子规则') {
      const { code, data } = await ruleCount({ id: record.id });
      setModelRuleVisible(true);
      if (code === 200 && data) {
        modalRuleForm.setFieldsValue({
          id: record.id,
          productKeyName: record.productKeyName,
          activityCount: data.activityCount,
          activityRuleCount: data.activityRuleCount,
        });
      }
      return;
    }

    if (type === '刷新activity') {
      const { code, data } = await activityCount({ id: record.id });
      if (code === 200 && data) {
        setSunDetail(data);
        modalReshForm.setFieldsValue({
          id: record.id,
          productKeyName: record.productKeyName,
          profileCount: data.profileCount,
          activityCount: data.activityCount,
          couponCount: data.couponCount,
          primeCount: data.primeCount,
          activityRuleCount: data.activityRuleCount,
        });
      }
      const res = await ruleCount({ id: record.id });
      setModelReshVisible(true);
      if (res.code === 200 && res.data) {
        setSunDetailBro(res.data);
        modalReshForm.setFieldsValue({
          activityRuleCount: res.data.activityRuleCount || 0,
        });
      }
      return;
    }

    if (['导出profile', '导出activity', '导出子规则'].includes(type)) {
      try {
        let resUpdate: any = {};
        if (type === '导出profile') {
          resUpdate = await exportProfile({ id: record.id });
        }
        if (type === '导出activity') {
          resUpdate = await exportActivity({ id: record.id });
        }
        if (type === '导出子规则') {
          resUpdate = await exportRule({ id: record.id });
        }
        const url = window.URL.createObjectURL(resUpdate.data);
        const link = document.createElement('a');
        link.style.display = 'none';
        const Disposition = resUpdate?.Disposition || '';
        if (!Disposition) {
          message.error('暂无数据');
          return;
        }
        link.download = decodeURIComponent(Disposition?.split(`filename*=utf-8''`)[1]) || `${type}`; // 下载的文件名称
        link.href = url;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        message.success('导出成功');
      } catch (error) {
        message.error('导出失败');
      }
      return;
    }

    confirm({
      content: `确认${type} 模板名：${record.productKeyName}？`,
      async onOk() {
        if (type === '同步PRE') {
          try {
            const { code, data } = await syncUat({ id: record.id });
            if (code === 200 && data) {
              message.success('操作成功');
              actionRef?.current?.reloadAndRest?.();
            } else {
              message.error('解锁失败');
            }
          } catch (error) {}
        }

        if (type === '删除') {
          try {
            const { code, data } = await productkeyDelete({ id: record.id });
            if (code === 200 && data) {
              message.success('操作成功');
              actionRef?.current?.reloadAndRest?.();
            } else {
              message.error('解锁失败');
            }
          } catch (error) {}
        }
      },
      onCancel() {},
    });
  };

  // 跳编辑页
  const hanldleEdit = (record: any) => {
    history.push(`/profile/productkey/modify/${record.id}`);
  };

  const hanldleAdd = () => {
    history.push(`/profile/productkey/add`);
  };

  const getItems = (record: API.CodegroupListItem) => {
    return (
      <Menu>
        <Menu.Item key="activity">
          <a onClick={() => handleOperate(record, '同步activity')}>同步activity</a>
        </Menu.Item>
        <Menu.Item key="rule">
          <a onClick={() => handleOperate(record, '同步子规则')}>同步子规则</a>
        </Menu.Item>
        <Menu.Item key="resh">
          <a onClick={() => handleOperate(record, '刷新activity')}>刷新activity</a>
        </Menu.Item>
        <Menu.Item key="outprofile">
          <a onClick={() => handleOperate(record, '导出profile')}>导出profile</a>
        </Menu.Item>
        <Menu.Item key="outactivity">
          <a onClick={() => handleOperate(record, '导出activity')}>导出activity</a>
        </Menu.Item>
        <Menu.Item key="sun">
          <a onClick={() => handleOperate(record, '导出子规则')}>导出子规则</a>
        </Menu.Item>
        <Menu.Item key="UAT">
          <a onClick={() => handleOperate(record, '同步PRE')}>同步PRE</a>
        </Menu.Item>
        <Menu.Item key="delete">
          <a onClick={() => handleOperate(record, '删除')}>删除</a>
        </Menu.Item>
        {/* {Number(record.codeCount) > 0 && (
          <Menu.Item key="batch">
            <a onClick={() => handleOperate(record, '批量销毁')}>批量销毁</a>
          </Menu.Item>
        )} */}
      </Menu>
    );
  };

  const columns: ProColumns<API.ProfileListItem>[] = [
    // 表单
    {
      title: '模板名',
      dataIndex: 'productKeyName',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '品牌ID',
      dataIndex: 'brandId',
      hideInTable: true,
      fieldProps: {
        placeholder: '请选择',
      },
      valueEnum: valueEnumActivityId,
    },
    // 表格
    {
      title: '模板名',
      dataIndex: 'productKeyName',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '品牌ID',
      dataIndex: 'brandId',
      ellipsis: true,
      width: 60,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '产品ID',
      dataIndex: 'productId',
      ellipsis: true,
      width: 160,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '产品规则ID',
      dataIndex: 'productIdRule',
      ellipsis: true,
      width: 160,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '后备产品码',
      dataIndex: 'productIdBackup',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '产品规则ID扩展属性',
      dataIndex: 'productIdRuleEx',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '产品ID扩展属性',
      dataIndex: 'productIdEx',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '后备产品码扩展属性',
      dataIndex: 'productIdBackupEx',
      ellipsis: true,
      width: 130,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 100,
      align: 'center',
      hideInSearch: true,
      fixed: 'right',
      render(_, record) {
        return (
          <div key={record.id}>
            <a onClick={() => hanldleEdit(record)}>修改</a>&nbsp;&nbsp;
            <Dropdown overlay={getItems(record)}>
              <a>
                更多 <DownOutlined />
              </a>
            </Dropdown>
          </div>
        );
      },
    },
  ];

  // 获取列表
  const getPromotionList = async (params: ParamsType) => {
    const { current, ...rest } = params;
    const param: any = {
      pageNo: current || 1,
      pageSize: params.pageSize || 10,
      ...rest,
    };

    const { code, data } = await productkeySearch(param);
    if (code === 200 && data) {
      const { rows, totalCount, pageSize, pageNo } = data;
      return {
        total: totalCount,
        pageSize,
        current: pageNo,
        data: rows,
      };
    }
    return {};
  };

  const showTotal: PaginationProps['showTotal'] = (t) => `共 ${t} 条`;

  const handleCountOK = () => {
    modalCountForm.validateFields().then(async (values) => {
      console.log('同步activity--', values);

      if (values.activityCount > 500) {
        message.info('更新量过大,不允许提交');
        return;
      }
      if (values.profileCount === 0 && values.activityCount === 0 && values.primeCount === 0) {
        message.info('更新量过大,不允许提交');
        return;
      }

      setConfirmLoad(true);
      const { code, data } = await syncActivity({
        id: values.id,
      });
      if (code === 200 && data) {
        message.success('操作成功');
        modalCountForm.resetFields();
        setModelCountVisible(false);
        actionRef?.current?.reloadAndRest?.();
      } else {
        message.success('无可更新数据');
        modalCountForm.resetFields();
        setModelCountVisible(false);
        actionRef?.current?.reloadAndRest?.();
      }
      setBusinessTypeList([]);
      setConfirmLoad(false);
    });
  };

  const handleCountCancel = () => {
    setModelCountVisible(false);
    modalCountForm.resetFields();
    setBusinessTypeList([]);
  };

  const handleRuleCancel = () => {
    setModelRuleVisible(false);
    modalRuleForm.resetFields();
  };

  const handlRuleOK = () => {
    modalRuleForm.validateFields().then(async (values) => {
      console.log('同步子规则--', values);
      if (values.activityCount > 500 || values.activityRuleCount > 500) {
        message.info('更新量过大,不允许提交');
        return;
      }
      if (values.activityCount === 0 && values.activityRuleCount === 0) {
        message.info('更新量过大,不允许提交');
        return;
      }
      setConfirmLoad(true);
      const { code, data } = await syncRule({
        id: values.id,
      });
      if (code === 200 && data) {
        message.success('操作成功');
        modalRuleForm.resetFields();
        setModelRuleVisible(false);
        actionRef?.current?.reloadAndRest?.();
      } else {
        message.success('无可更新数据');
        modalRuleForm.resetFields();
        setModelRuleVisible(false);
        actionRef?.current?.reloadAndRest?.();
      }
      setConfirmLoad(false);
    });
  };

  const handleReshCancel = () => {
    setModelReshVisible(false);
    modalReshForm.resetFields();
  };

  const handleReshOK = () => {
    if (sunDetail.activityCount > 500 || sunDetailBro.activityRuleCount > 500) {
      message.info('更新量过大,不允许提交');
      return;
    }
    modalReshForm.validateFields().then(async (values) => {
      if (values.activityCount === 0 && values.primeCount === 0 && values.activityRuleCount === 0) {
        message.info('更新量过大,不允许提交');
        return;
      }
      setConfirmLoad(true);
      const { code, data } = await refreshActivity({
        id: values.id,
      });
      if (code === 200 && data) {
        message.success('操作成功');
        modalReshForm.resetFields();
        setModelReshVisible(false);
        actionRef?.current?.reloadAndRest?.();
      } else {
        // message.success('无可更新数据');
        modalReshForm.resetFields();
        setModelReshVisible(false);
        actionRef?.current?.reloadAndRest?.();
      }
      setConfirmLoad(false);
    });
  };

  return (
    <PageContainer>
      <div className={styles['form-body']}>
        <ProTable<API.ActivatecodeListItem>
          rowKey="id"
          columns={columns}
          actionRef={actionRef}
          formRef={formRef}
          // @ts-ignore
          request={getPromotionList}
          options={false}
          search={{
            optionRender: (searchConfig, props, dom) => [...dom],
          }}
          toolBarRender={() => [
            <Button type="primary" key="add" onClick={() => hanldleAdd()}>
              新增
            </Button>,
          ]}
          scroll={{ x: 800 }}
          pagination={{
            showSizeChanger: true,
            size: 'small',
            showTotal,
            showQuickJumper: true,
            defaultPageSize: 10,
          }}
        />

        <Modal
          title="同步activity"
          width={520}
          open={modelCountVisible}
          onOk={handleCountOK}
          onCancel={handleCountCancel}
          confirmLoading={confirmLoad}
          okText="确认"
        >
          <Tag color="error" style={{ width: '100%', marginBottom: 24 }}>
            请仔细核对数量
          </Tag>
          <Form
            labelCol={{ span: 6 }}
            form={modalCountForm}
            initialValues={{
              id: '',
              productKeyName: '',
              profileCount: '',
              activityCount: '',
              couponCount: '',
              primeCount: '',
            }}
          >
            <Form.Item label="id" name="id" hidden={true}>
              <Input disabled={true} />
            </Form.Item>
            <Form.Item label="模版名称" name="productKeyName">
              <Input disabled={true} />
            </Form.Item>
            <Form.Item label="主档总数" name="profileCount">
              <Input disabled={true} />
            </Form.Item>

            {businessTypeList &&
              businessTypeList.map((item: any, index: number) => {
                return (
                  <Form.Item label={item.type} key={index}>
                    <Input value={item.count} disabled={true} />
                  </Form.Item>
                );
              })}
            {/* <Form.Item label="Prime卡套" name="storeId">
              <Input disabled={true} />
            </Form.Item>
            <Form.Item label="券" name="storeId">
              <Input disabled={true} />
            </Form.Item> */}
            <Form.Item label="activity总数" name="activityCount">
              <Input disabled={true} />
            </Form.Item>
            <Form.Item label="券总数" name="couponCount">
              <Input disabled={true} />
            </Form.Item>
            <Form.Item label="Prime总数" name="primeCount">
              <Input disabled={true} />
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title="同步子规则"
          width={520}
          open={modelRuleVisible}
          onOk={handlRuleOK}
          onCancel={handleRuleCancel}
          confirmLoading={confirmLoad}
          okText="确认"
        >
          <Tag color="error" style={{ width: '100%', marginBottom: 24 }}>
            请仔细核对数量
          </Tag>
          <Form
            labelCol={{ span: 6 }}
            form={modalRuleForm}
            initialValues={{
              id: '',
              productKeyName: '',
              activityCount: '',
              activityRuleCount: '',
            }}
          >
            <Form.Item label="id" name="id" hidden={true}>
              <Input disabled={true} />
            </Form.Item>
            <Form.Item label="模板名" name="productKeyName">
              <Input disabled={true} />
            </Form.Item>
            <Form.Item label="activity总数" name="activityCount">
              <Input disabled={true} />
            </Form.Item>
            <Form.Item label="子规则总数" name="activityRuleCount">
              <Input disabled={true} />
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title="刷新activity"
          width={520}
          open={modelReshVisible}
          onOk={handleReshOK}
          onCancel={handleReshCancel}
          confirmLoading={confirmLoad}
          okText="确认"
        >
          <Tag color="error" style={{ width: '100%', marginBottom: 24 }}>
            {sunDetail.activityCount > 500 || sunDetailBro.activityRuleCount > 500
              ? '更新量过大,不允许提交'
              : '请仔细核对数量'}
          </Tag>
          <Form
            labelCol={{ span: 6 }}
            form={modalReshForm}
            initialValues={{
              id: '',
              productKeyName: '',
              profileCount: '',
              activityCount: '',
              couponCount: '',
              primeCount: '',
              activityRuleCount: '',
            }}
          >
            <Form.Item label="id" name="id" hidden={true}>
              <Input disabled={true} />
            </Form.Item>
            <Form.Item label="模板名" name="productKeyName">
              <Input disabled={true} />
            </Form.Item>
            <Form.Item label="activity总数" name="activityCount">
              <Input disabled={true} />
            </Form.Item>
            <Form.Item label="券总数" name="couponCount">
              <Input disabled={true} />
            </Form.Item>
            <Form.Item label="Prime总数" name="primeCount">
              <Input disabled={true} />
            </Form.Item>
            <Form.Item label="子规则总数" name="activityRuleCount">
              <Input disabled={true} />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </PageContainer>
  );
};

export default SensitizeManageList;
